<?php
use think\Db;
use Wechat\Loader;

/*
 *    版本号比较  by sam 20170412
 *    @param $version1 版本A 如:5.3.2
 *    @param $version2 版本B 如:5.3.0
 *    @return int -1版本A小于版本B , 0版本A等于版本B, 1版本A大于版本B
 *
 *    版本号格式注意：
 *        1.要求只包含:点和大于等于0小于等于2147483646的整数 的组合
 *        2.boole型 true置1，false置0
 *        3.不设位默认补0计算，如：版本号5等于版号5.0.0
 *        4.不包括数字 或 负数 的版本号 ,统一按0处理
 *
 *    @example:
 *       if (versionCompare('5.2.2','5.3.0')<0) {
 *            echo '版本1小于版本2';
 *       }
 */
function apk_verison_compare($versionA, $versionB) {
	if ($versionA > 2147483646 || $versionB > 2147483646) {
		throw new Exception('版本号,位数太大暂不支持!', '101');
	}
	$dm = '.';
	$verListA = explode($dm, (string)$versionA);
	$verListB = explode($dm, (string)$versionB);

	$len = max(count($verListA), count($verListB));
	$i = -1;
	while ($i++ < $len) {
		$verListA[$i] = intval(@$verListA[$i]);
		if ($verListA[$i] < 0) {
			$verListA[$i] = 0;
		}
		$verListB[$i] = intval(@$verListB[$i]);
		if ($verListB[$i] < 0) {
			$verListB[$i] = 0;
		}

		if ($verListA[$i] > $verListB[$i]) {
			return 1;
		} else if ($verListA[$i] < $verListB[$i]) {
			return -1;
		} else if ($i == ($len - 1)) {
			return 0;
		}
	}

}

/**
 * =========================
 * =======业务扩展 函数库=======
 * =========================
 */

/**
 * 获得工资范围
 */
function get_comment_score($id = 0, $array = false) {
	if ($array) {
		$types['3'] = '好评';
		$types['2'] = '中评';
		$types['1'] = '差评';
		return $types;
	} else {
		switch($id) {
			case 3 :
				return '好评';
				break;
			case 2 :
				return '中评';
				break;
			case 1 :
				return '差评';
				break;
			default :
				return null;
				break;
		}
	}
}


/**
 * 获得订单状态
 */
function get_order_type($id = 0, $array = false) {
	if ($array) {
		$types['1'] = '待付款';
		$types['2'] = '待发货';
		$types['3'] = '待收货';
		$types['4'] = '待评价';
		$types['5'] = '已完成';
		$types['6'] = '已预定';
		$types['9'] = '已关闭';
		return $types;
	} else {
		switch($id) {
			case 1 :
				return '待付款';
				break;
			case 2 :
				return '待发货';
				break;
			case 3 :
				return '待收货';
				break;
			case 4 :
				return '待评价';
				break;
			case 5 :
				return '已完成';
				break;
			case 6 :
				return '已预定';
				break;
			case 9 :
				return '已关闭';
				break;
			default :
				return null;
				break;
		}
	}
}


/**
 * 获取微信操作对象
 * @staticvar array $wechat
 * @param type $type
 * @return WechatReceive
 */
function load_wechat($type = '') {
	$wechat = array();
	$index = md5(strtolower($type));
	if (!isset($wechat[$index])) {
		$config = db('system')->where('name','wechat_config')->find();
		$config['cachepath'] = CACHE_PATH . 'wechat';
		$wechat[$index] = Wechat\Loader::get($type, $config);
	}
	return $wechat[$index];
}

/**
 * =========================
 * ========通用 函数库=========
 * =========================
 */


function strFilter($str) {
	$str = str_replace('·', '', $str);
	$str = str_replace('~', '', $str);
	$str = str_replace('!', '', $str);
	$str = str_replace('@', '', $str);
	$str = str_replace('#', '', $str);
	$str = str_replace('$', '', $str);
	$str = str_replace('%', '', $str);
	$str = str_replace('^', '', $str);
	$str = str_replace('&', '', $str);
	$str = str_replace('*', '', $str);
	$str = str_replace('(', '', $str);
	$str = str_replace(')', '', $str);
	$str = str_replace('-', '', $str);
	$str = str_replace('_', '', $str);
	$str = str_replace('——', '', $str);
	$str = str_replace('+', '', $str);
	$str = str_replace('=', '', $str);
	$str = str_replace('|', '', $str);
	$str = str_replace('\\', '', $str);
	$str = str_replace('[', '', $str);
	$str = str_replace(']', '', $str);
	$str = str_replace('{', '', $str);
	$str = str_replace('}', '', $str);
	$str = str_replace(';', '', $str);
	$str = str_replace(':', '', $str);
	$str = str_replace('\'', '', $str);
	$str = str_replace('"', '', $str);
	$str = str_replace(',', '', $str);
	$str = str_replace('<', '', $str);
	$str = str_replace('>', '', $str);
	$str = str_replace('.', '', $str);
	$str = str_replace('/', '', $str);
	$str = str_replace('?', '', $str);
	return trim($str);
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
	$units = array(
		' B',
		' KB',
		' MB',
		' GB',
		' TB',
		' PB'
	);
	for ($i = 0; $size >= 1024 && $i < 5; $i++)
		$size /= 1024;
	return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 获取当前request参数数组,去除值为空
 * @return array
 */
function get_query() {
	$param = request()->except(array('s'));
	$rst = array();
	foreach ($param as $k => $v) {
		if (!empty($v)) {
			$rst[$k] = $v;
		}
	}
	return array('query' => $rst);
}

/**
 * 数组里删除指定key的数据
 */
function array_remove($data, $key) {
	if (!array_key_exists($key, $data)) {
		return $data;
	}
	$keys = array_keys($data);
	$index = array_search($key, $keys);
	if ($index !== FALSE) {
		array_splice($data, $index, 1);
	}
	return $data;
}

/**
 * 数组层级缩进转换
 * @param array $array
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1) {
	static $list = array();
	foreach ($array as $v) {
		if ($v['pid'] == $pid) {
			$v['level'] = $level;
			$list[] = $v;
			array2level($array, $v['id'], $level + 1);
		}
	}

	return $list;
}

/**
 * 构建层级（树状）数组
 * @param array  $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid = 'pid', $child_key_name = 'children') {
	$counter = array_children_count($array, $pid);
	if ($counter[0] == 0) {

		return false;
	}
	$tree = array();
	while (isset($counter[0]) && $counter[0] > 0) {
		$temp = array_shift($array);
		if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
			array_push($array, $temp);
		} else {
			if ($temp[$pid] == 0) {
				$tree[] = $temp;
			} else {
				$array = array_child_append($array, $temp[$pid], $temp, $child_key_name);
			}
		}
		$counter = array_children_count($array, $pid);
	}
	return $tree;
}

/**
 * 子元素计数器
 * @param $array
 * @param $pid
 * @return array
 */
function array_children_count($array, $pid) {
	$counter = array();
	foreach ($array as $item) {
		$count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
		$count++;
		$counter[$item[$pid]] = $count;
	}

	return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name) {
	foreach ($parent as &$item) {
		if ($item['id'] == $pid) {
			if (!isset($item[$child_key_name]))
				$item[$child_key_name] = array();
			$item[$child_key_name][] = $child;
		}
	}

	return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
	$result = false;
	if (is_dir($dir_name)) {
		if ($handle = opendir($dir_name)) {
			while (false !== ($item = readdir($handle))) {
				if ($item != '.' && $item != '..') {
					if (is_dir($dir_name . DS . $item)) {
						delete_dir_file($dir_name . DS . $item);
					} else {
						unlink($dir_name . DS . $item);
					}
				}
			}
			closedir($handle);
			if (rmdir($dir_name)) {
				$result = true;
			}
		}
	}
	return $result;
}

function build_order_no() {
	return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}


/********************************** 2018-03-18 ***************************************************************/

/******************************====  公共函数 stat ======******************************/

//图片上传
function upload($files){
	include_once ('././vendor/aliyuncs/oss-sdk-php/autoload.php');
    $tmp = base64_decode($files);
    $fn = time()."_".rand(100000, 999999) . ".jpg";
	$fp = '././uploads/image/'. $fn;
	$fp1 = '././uploads/image/'. $fn;
    $res=file_put_contents( $fp, $tmp);
	$ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
	try{
		$res=$ossClient->uploadFile("long3",$fn,$fp1);
		$src='https://long3.oss-cn-shanghai.aliyuncs.com/'.$fn;
		unlink($fp1);
		return json(["code"=>200,'url'=>$src]);
	} catch(OssException $e) {
		return json(["code"=>404,'msg'=>'上传错误']);
	} 
} 

//新增
function add_data($table_name,$data){
	$result = db($table_name)->insert($data);
	return $result;
}

//删除
function del_data($table_name,$id){
	$result = db($table_name)->delete($id);
	return $result;
}

//更新数据
function update_data($table_name,$data){
	$result = db($table_name)->update($data);
	return $result;
}

//查找单条数据
function select_data($table_name,$where){
	$data = db($table_name)->where($where)->find();
	return $data;
}


/**
 *获取分佣设置 
 */
function get_config(){
	$sys_config = db('system')->where('name','sys_config')->find();
   	return unserialize($sys_config['value']);
}

 
 /**
 * 返回格式化后的当前时间
 */
function now_time() {
	return date('YmdHis', time()).rand(8, true).time();
}


/*
 * 加密--32位密码
 */
function md5_salt($password) {
	return md5(crypt($password, config('salt')));
}

/**
 * 生成订单号
 */
function order_create_no(){
	return date('YmdHis', time()).rand(8, true).time();
}


//function sendsms($sign,$mobile,$tempid,$name,$value,$user_ip){
//	$cut_time = now_time();
//	include_once ('/extend/smsapi/smsDemo.php');
//	$msg=sendMess($sign,$mobile,$tempid,$name,$value);
//	if($msg->Message=="OK") {
//		$data['mobile'] 	= $mobile;
//		$data[$name] 		= $value;
//		$data['add_time'] 	= $cut_time;
//		$data['message'] 	= '发送成功';
//		//$data['user_ip'] 	= $user_ip;
//		db('verify_code')->insert($data);
//		return true;
//	}else{
//		$data['mobile'] 	= $mobile;
//		$data[$name] 		= $value;
//		$data['add_time'] 	= $cut_time;
//		$data['result'] 	= 0;
//		$data['message'] 	= '发送失败:'.$msg->Message;
//		//$data['user_ip'] 	= $user_ip;
//		db('verify_code')->insert($data);
//		$err=$msg->Message;
//		return false;
//	}
//}
/*
 * 检查验证码
 * */ 
function check_sendcode($mobile, $code, $message){
	$where['mobile'] = $mobile;
	$where['code'] = $code;
	$where['message'] = '发送成功';
	$result =db('verify_code')->where($where)->find();
	// 10分钟有效期
	if(time() - strtotime($result['add_time']) > 600){
		return 2;
	}
	if($code == $result['code']){
		return 1;
	}else{
		return -1;
	}
}
	
/**
 * 发送短信验证
 * $mobile 手机号
 * $template_no 模板编号(数据库主键)，注意不是模板ID
 */
//function get_code($mobile,$user_ip){
//	// 获取短信模板
//	$tem_w['title']='用户注册';
//	
//	$template = db("sys_template")->where($tem_w)->find();
//	// 如果是验证码类型，则生成6位验证码
//	if($template['type'] == 1){
//		$code = rand(10000, 99999);
//		$template['params'] = str_replace('${code}', $code, $template['params']);
//		$data['code'] = $code;
//	}
//	$msg=sendsms($template['sign_name'],$mobile,$template['tid'],'code',$code,$user_ip);
//	if($msg){
//		return json(["code"=>200,"msg"=>'发送成功!']); 
//	}else{
//		return json(["code"=>408,"msg"=>'发送失败']); 
//	}
//}

/**
 * 	$goods_list 商品信息
 * 	$memo		订单留言
 *	$address_id 收货地址id
 * 	$order_type 付款类型
 * 
 * 生成订单，
 */
function add_order($goods_list,$order_sn,$type=1){
	$total_price = 0;
	if ($type == 1) {
		
		$price = bcmul($goods_list['cost_price'],$goods_list['goods_num'], 2);
		$total_price = bcadd($price, $total_price, 2);
		$agent_info = db('agent')->where('id',$goods_list['agent_id'])->find();
	}else{
		foreach($goods_list as $key=>$value){
			$price = bcmul($value['cost_price'],$value['goods_num'], 2);
			$total_price = bcadd($price, $total_price, 2);
		}
		
		$agent_info = db('agent')->where('id',$goods_list[0]['agent_id'])->find();
	}
	
	
	$order_info['order_sn'] 	= $order_sn;
	$order_info['user_id'] 		= session('user_id');
	$order_info['agent_id'] 	= $agent_info['id'];
	$order_info['agent_name'] 	= $agent_info['agent_name'];
	$order_info['total_price'] 	= $total_price; 
	$order_info['add_time'] 	= now_time();
	
	return db('good_order')->insert($order_info);
}

//更新订单
function update_order($order_id,$order_type,$address_id,$memo){
	
	//获取收货人信息
	$user_address = db('member_address')->where('id',$address_id)->find();

	$order_info['order_type'] 	= $order_type;
	$order_info['consignee'] 	= $user_address['consignee'];
	$order_info['province'] 	= $user_address['province'];
	$order_info['city'] 		= $user_address['city'];
	$order_info['district']	 	= $user_address['district'];
	$order_info['address'] 		= $user_address['address'];
	$order_info['mobile'] 		= $user_address['mobile'];
	$order_info['memo'] 		= $memo;
	
	return db('good_order')->where('id', $order_id)->update($order_info);
}


//生成订单详情
function add_order_item($goods_list,$order_id,$type=1){
	$result =true;
	
	if ($type == 1) {
		
	    $total_price = bcmul($goods_list['cost_price'],$goods_list['goods_num'], 2);
	    
		$item_info['order_id'] 		= $order_id;
		$item_info['goods_id'] 		= $goods_list['goods_id'];
		$item_info['nums'] 			= $goods_list['goods_num'];
		$item_info['total_price'] 	= $total_price;
		$item_info['price'] 		= $goods_list['cost_price'];
		$item_info['goods_name'] 	= $goods_list['goods_name'];
		$item_info['thumb'] 		= $goods_list['logo'];
		$item_info['express_type'] 	= $goods_list['express_type'];
		$item_info['add_time'] 		= now_time();
		
		$rest =  db('order_items')->insert($item_info);
		if(!$rest)$result= false;
		
	} else {
	   foreach($goods_list as $key=>$value){
		   	$total_price = bcmul($value['cost_price'],$value['goods_num'], 2);
			
			$item_info['order_id'] 		= $order_id;
			$item_info['goods_id'] 		= $value['goods_id'];
			$item_info['nums'] 			= $value['goods_num'];
			$item_info['total_price'] 	= $total_price;
			$item_info['price'] 		= $value['cost_price'];
			$item_info['goods_name'] 	= $value['goods_name'];
			$item_info['thumb'] 		= $value['logo'];
			$item_info['express_type'] 	= $value['express_type'];
			$item_info['add_time'] 		= now_time();
			
			$rest =  db('order_items')->insert($item_info);
			if(!$rest)$result= false;
	   }
	}
	
	return $result;
}


/*==================================>日志回调函数==================================*/

//付款成功
function add_corepaylog($paylog_id){
	$result = true;
	$paylog = db('paylog')->where('id',$paylog_id)->find();
	if($paylog){
		//更新日志状态
		$rest1 = db('paylog')->where('id', $paylog['id'])->update(['state' => 2,'pay_time'=>now_time()]);
		if(!$rest1) $result = false;
		
		unset($paylog['id']);
		$paylog['state'] = 2;
		$paylog['pay_time'] = now_time();
		
		$rest2 = db('paylog_copy')->insert($paylog);
		if(!$rest2) $result = false;
	}else{
		$result = false;
	}
	
	return $result;
}

//支付回调
function pay_callback($order_sn){
	//获取支付日志
	$paylog = db('paylog')->where('order_sn',$order_sn)->find();
	 
	//获取付款用户信息
	$pay_user_info = db('member')->where('user_id',$paylog['user_id'])->find();
	
	if($paylog['order_type'] == 1){			//参与跑步活动充值
		//获取分佣设置
		$commission_config = get_config();
		
		$result = true;
		Db::startTrans();
		//新增运动充值记录
		$rest1 = add_sports_charge($pay_user_info['user_id'],$paylog['balance'],$paylog['order_sn'],0);
		if(!$rest1)$result = false;
		/*
		//按地区查找代理
		$oem_info = db('oem') ->where('town_name_id',$pay_user_info['district_id'])->find();
		//检查用户是否有区县
		if($oem_info){
			//计算区县代佣金
			$county_commission = bcmul($commission_config['county_commission']/100, $paylog['balance'], 2);
			
			//新增代理商余额
			$rest6 = db('oem')->where('id', $oem_info['id'])->setInc('balance',$county_commission);
			if(!$rest6)$result = false;
			//新增代理商累计收入
			$rest11 = db('oem')->where('id', $oem_info['id'])->setInc('total_income',$county_commission);
			if(!$rest11)$result = false;
			//代理商余额变化日志
			$rest7 =  add_oem_charge($oem_info['id'],1,$paylog['order_sn'],$county_commission,'推荐会员'.$pay_user_info['mobile']."充值分佣");
			if(!$rest7)$result = false;
		}
		*/
		//用户上级分佣 
		if($pay_user_info['pid1'] > 0){
			//计算上级佣金
			$pt_commission = bcmul($commission_config['level1_commission']/100, $paylog['balance'], 2);
			
			//新增上级余额
			$rest9 = db('member')->where('user_id', $pay_user_info['pid1'])->setInc('money',$pt_commission);
			if(!$rest9)$result = false;
			//新增上级累计收入
			$rest12 = db('member')->where('user_id', $pay_user_info['pid1'])->setInc('total_income',$pt_commission);
			if(!$rest12)$result = false;
			
			//余额变化日志
			$rest10 =  add_member_charge($pay_user_info['pid1'],$pt_commission,5,$paylog['order_sn'],'推荐会员'.$pay_user_info['mobile']."充值分佣");
			if(!$rest10)$result = false;
		}
		
		$rest8 =  add_corepaylog($paylog['id']);
		if(!$rest8)$result = false;
		
		if($result){
			// 提交事务
		    Db::commit();    
		}else{
			// 回滚事务
		    Db::rollback();
		}
		
		
	}elseif($paylog['order_type'] == 2){		//商城消费
		//获取商家信息
		$agent_info = db('agent')->where('id',$paylog['agent_id'])->find();
		//获取订单信息
		$order_inof = db('good_order')->where('id',$paylog['order_id'])->find();		
		//获取订单详情 
		$order_items = db('order_items')->where('order_id',$order_inof['id'])->select();		
		
		/*******用户的资金变化，在用户购买商品时扣除余额**********/
		
		$result = true;
		//新增商家余额
		$rest1 = db('agent')->where('id', $agent_info['id'])->setInc('balance',$paylog['balance']);
		if(!$rest1)$result = false;
		
		//商家余额变化日志
		$rest2 =  add_agent_charge($agent_info['id'],$paylog['balance'],2,$paylog['order_sn'],'用户'.$pay_user_info['mobile'].'购买商品',1);
		if(!$rest2)$result = false;
		
		//修改订单状态
		$rest3 = db('good_order')->where('id', $order_inof['id'])->update(['status' => '2']);
		if(!$rest3)$result = false;
		
		//商品数量变化
		foreach($order_items as $key=>$value){
			
			//获取商品信息
			$goods_info = db('goods')->where('goods_id', $value['goods_id'])->find();
			//计算库存
			$stock = $goods_info['stock'] - $value['nums'];
			//减商品库存														
			$rest5 = db('goods')->where('goods_id', $goods_info['goods_id'])->update(['stock'=>$stock]);
			if(!$rest5) $result = false;
			
		}
		
		$rest4 =  add_corepaylog($paylog['id']);
		if(!$rest4)$result = false;
			
		return $result;
	}elseif($paylog['order_type'] == 3){
		$result = true;
		Db::startTrans();
		
		//新增用户小卡金额
		$rest1 = db('member')->where('user_id', $paylog['user_id'])->setInc('score', $paylog['balance']);
		if(!$rest1) $result = false;
		
		//用户小卡变化记录
		$rest2 = add_member_consume($paylog['user_id'],$paylog['balance'],$paylog['order_sn'],$paylog['order_type'],"购买会员小卡");
		if(!$rest2) $result = false;
		
		if($result){
			// 提交事务
		    Db::commit();    
		}else{
			// 回滚事务
		    Db::rollback();
		}
		
	}
	
}


/**
 *用户完成运动任务 
 */
function spost_finish($user_id,$sports_id){
	//获取用户充值信息
	$sports_list = db('sports_charge')->where('user_id',$user_id)->where('status',1)->select();
	if(!$sports_list){
		return false;
	}
	$result = true;
	Db::startTrans();
	$total_fx = 0;	//统计当日总返现金额
	//检查当前任务是否返现
	$sports_info = db('sports')->where('id',$sports_id)->find();
	
	//当前任务未返现
	if($sports_info['is_fx'] == 1){
		foreach($sports_list as $key=>$value){
			//获取用户信息
			$user_info = db('member')->where('user_id',$user_id)->find();
			//本次返现金额
			$cut_back_money = 0;
			
			
			if($value['status'] == 1){
				//计算时间
				$startdate=strtotime($value['add_time']); 
				$enddate=strtotime(date('Y-m-d'));
				$days=round(($enddate-$startdate)/3600/24) ; 
				
				if($days <= 200){
					$cut_back_money = $value['once_money'];
				}else if($days <= 400){
					
					$cut_add_time = $value['add_time'];
					
					$days_200 = date('Y-m-d',strtotime("$cut_add_time +200 day"));
					//计算第一期总返现金额
					$one_tatol_money = db('member_charge')
											->where('user_id',$value['user_id'])
											->whereTime('add_time', 'between', [$cut_add_time,$days_200])
											->sum('balance');
					//计算第二期返现金额
					$cut_back_money = bcdiv($one_tatol_money, 200, 2);
				}else if($days <= 600){
					$is_time = $value['add_time'];					
					$cut_add_time = date('Y-m-d',strtotime("$is_time +200 day"));
					
					$days_200 = date('Y-m-d',strtotime("$cut_add_time +200 day"));
					//计算第三期总返现金额
					$two_tatol_money = db('member_charge')
											->where('user_id',$value['user_id'])
											->whereTime('add_time', 'between', [$cut_add_time, $days_200])
											->sum('balance');
					//计算第三期返现金额
					$cut_back_money = bcdiv($two_tatol_money, 200, 2);
				}else{
					
					//更新用户充值返现信息
					$rest5 = db('sports_charge')->where('id', $value['id'])->update(['status'=>2]);
					// 提交事务
	    			Db::commit();  
					return false;
				}

				$total_fx = bcadd($total_fx, $cut_back_money, 2);
				
				//获取分佣设置 yue_commission xf_commission gy_commission
				$commission_config = get_config();
				
				//计算大卡,小卡,公益金额
				$big_money = bcmul($commission_config['yue_commission']/100, $cut_back_money, 2);
				$mini_money = bcmul($commission_config['xf_commission']/100, $cut_back_money, 2);
				$gy_money = bcmul($commission_config['gy_commission']/100, $cut_back_money, 2);
				
				$cut_moeny = bcadd($user_info['money'], $big_money, 2);
				$cut_score = bcadd($user_info['score'], $mini_money, 2);
				$cut_gongyi = bcadd($user_info['gongyi'], $gy_money, 2);
				
				//更新用户金额变化
				$rest1 = db('member')
						->where('user_id', $user_info['user_id'])
						->update(['money' => $cut_moeny,'score'=>$cut_score,'gongyi'=>$cut_gongyi]);
				if(!$rest1) $result = false;
				//大卡余额记录
				$rest2 = add_member_charge($user_info['user_id'],$big_money,4,0,$sports_info['add_time']."完成运动任务奖励大卡金额".$big_money,$value['id']);
				if(!$rest2) $result = false;
				
				//小卡余额记录
				$rest3 = add_member_consume($user_info['user_id'],$mini_money,0,5,$sports_info['add_time']."完成运动任务小卡金额".$mini_money,$value['id']);
				if(!$rest3) $result = false;
				
				//公益余额记录
				$rest4 = add_member_gongyi($user_info['user_id'],$gy_money,0,5,$sports_info['add_time']."完成运动任务奖励公益金额".$gy_money,$value['id']);
				if(!$rest4) $result = false;
				
				//计算用户已返现金额
				$back_money = bcadd($cut_back_money, $value['back_money'], 2);
				//计算用户未返现金额
				$notback_money = bcsub($value['balance']*3, $back_money, 2);
				//计算用户完成任务次数
				$achieve_num = $value['achieve_num'] +1;
				
				
				$data['back_money'] = $back_money;
				$data['notback_money'] = $notback_money;
				$data['achieve_num'] = $achieve_num;
				
				//更新用户充值返现信息
				$rest5 = db('sports_charge')->where('id', $value['id'])->update($data);
				if(!$rest5) $result = false;
			}
		}
		
		//更新当日返现情况
		$rest6 = db('sports') ->where('id', $sports_info['id'])->update(['fx_balance'=>$total_fx,'fx_time'=>now_time()]);
		if(!$rest6) $result = false;
	}else{
		$result = false;
	}
	
	if($result){
		// 提交事务
	    Db::commit();    
	}else{
		// 回滚事务
	    Db::rollback();
	}
	
	return $result;
}


/**
 * 用户余额变化日志
 */
function add_member_charge($user_id,$balance,$order_type,$order_sn,$message,$sport_id=0){
 		$data['user_id'] 		= $user_id;
 		$data['balance']		= $balance;
 		$data['order_type']		= $order_type;
 		$data['order_sn']		= $order_sn;
 		$data['message']		= $message;
 		$data['sport_change_id']= $sport_id;
 		$data['add_time']		= now_time();
 		return db('member_charge')->insert($data);
 }
 /**
 * 用户余额提现日志
 */
 function add_member_tixian($user_id,$money,$withdraw_type,$sxf_money,$dz_money){
 	//获取oem认证信息
	$user_verif = db('member_verif')->where('user_id',$user_id)->find();
	
	$data['user_id'] 		= $user_verif['user_id'];
	$data['balance']		= $money;
	$data['withdraw_type']	= $withdraw_type;
	$data['sxf_money']		= $sxf_money;
	$data['dz_money']		= $dz_money;
	
	$data['bank_name']		= $user_verif['bank_name'];
	$data['account_bank']	= $user_verif['bank_no'];
	$data['account_name']	= $user_verif['user_name'];
	$data['bank_mobile']	= $user_verif['reserve_mobile'];
	
	$data['add_time']		= now_time();
	
	return db('member_tixian')->insert($data);
 }
 
 
 
 
/**
 * 商家余额变化日志
 */
function add_agent_charge($agent_id,$balance,$order_type,$order_sn,$message,$status){
 		$data['agent_id'] 		= $agent_id;
 		$data['balance']		= $balance;
 		$data['order_type']		= $order_type;
 		$data['order_sn']		= $order_sn;
 		$data['message']		= $message;
 		$data['status']			= $status;
 		$data['add_time']		= now_time();
 		
 		return db('agent_charge')->insert($data);
 }
 /**
  *商家提现日志 
  */
function add_agent_tixan($agent_id,$money,$withdraw_type,$sxf_money,$dz_money){
	
	//获取oem认证信息
	$agent_verif = db('agent_verif')->where('agent_id',$agent_id)->find();
	
	$data['agent_id'] 		= $agent_verif['agent_id'];
	$data['balance']		= $money;
	$data['withdraw_type']	= $withdraw_type;
	$data['sxf_money']		= $sxf_money;
	$data['actual_balance']	= $dz_money;
	
	$data['bank_account']	= $agent_verif['bank_name'];
	$data['bank_no']		= $agent_verif['bank_no'];
	$data['bank_username']	= $agent_verif['user_name'];
	$data['bank_mobile']	= $agent_verif['reserve_mobile'];
	$data['add_time']		= now_time();
	
	return db('agent_tixian')->insert($data);
 }
 
 

/**
 * 代理余额变化日志 
 */
function add_oem_charge($oem_id,$order_type,$order_sn,$balance,$message){
 		$data['oem_id'] 		= $oem_id;
 		$data['order_type']		= $order_type;
 		$data['order_sn']		= $order_sn;
 		$data['balance']		= $balance;
 		$data['message']		= $message;
 		$data['add_time']		= now_time();
 		
 		return db('oem_charge')->insert($data);
 }

/**
 * 代理提现日志 
 */
 function add_oem_tixan($oem_id,$money,$withdraw_type,$sxf_money,$dz_money){
	
	//获取oem认证信息
	$oem_verif = db('oem_verif')->where('oem_id',$oem_id)->find();
	
	$data['oem_id'] 		= $oem_id;
	$data['money']			= $money;
	$data['withdraw_type']	= $withdraw_type;
	$data['sxf_money']		= $sxf_money;
	$data['dz_money']		= $dz_money;
	
	$data['bank_name']		= $oem_verif['bank_name'];
	$data['account_no']		= $oem_verif['bank_no'];
	$data['account_name']	= $oem_verif['user_name'];
	$data['bank_mobile']	= $oem_verif['reserve_mobile'];
	$data['add_time']		= now_time();
	
	return db('oem_tixian')->insert($data);
 }

 
 
 /**
 * 用户消费金额变化日志
 */
 function add_member_consume($user_id,$balance,$order_sn,$order_type,$message="",$sport_id=0){
 		$data['user_id'] 			= $user_id;
 		$data['balance']			= $balance;
 		$data['order_sn']			= $order_sn;
 		$data['order_type']			= $order_type;
		$data['message']			= $message;
		$data['sport_change_id']	= $sport_id;
 		$data['add_time']			= now_time();
 		
 		return db('member_consume')->insert($data);
 }
 
 /**
  *用户公益变化日志 
  */
  function add_member_gongyi($user_id,$balance,$order_sn,$order_type,$message="",$sport_id=0){
 		$data['user_id'] 			= $user_id;
 		$data['balance']			= $balance;
		$data['message']			= $message;
		$data['order_type']			= $order_type;
		$data['order_sn']			= $order_sn;
		$data['sport_change_id']	= $sport_id;
 		$data['add_time']			= now_time();
 		
 		return db('member_gongyi')->insert($data);
 }
 
 
 
 /**
  *  运动充值记录
  */
 function add_sports_charge($user_id,$balance,$order_sn,$achieve_num){
 		$data['user_id'] 		= $user_id;
 		$data['balance']		= $balance;
 		$data['order_sn']		= $order_sn;
 		$data['achieve_num']	= 0;
 		$data['status']			= 1;
 		$data['back_money']		= 0;
 		$data['notback_money']	= $balance;
 		$data['once_money']		= bcdiv($balance, 200, 2);
 		$data['add_time']		= now_time();
 		
 		return db('sports_charge')->insert($data);
 }
 

 /**
  * 支付日志
  */
 function add_pay_log($user_id,$agent_id,$balance,$order_type,$order_sn,$pay_type,$state,$message,$order_id,$pay_time){
 	
	$data['user_id']  	= $user_id;
	$data['agent_id']  	= $agent_id;
	$data['balance']  	= $balance;
	$data['order_type'] = $order_type;
	$data['order_sn']  	= $order_sn;
	$data['pay_type'] 	= $pay_type;
	$data['state']  	= $state;
	$data['message'] 	= $message;
	$data['order_id']  	= $order_id;
	$data['pay_time']  	= $pay_time;
	$data['add_time']  	= now_time();
	
	return db('paylog')->insert($data);
 }
 

 function get_type_charge($id = 1) {
	switch($id) {
		case 1 :
			return '提现';
			break;
		case 2 :
			return '二维码付款';
			break;
		case 3 :
			return '提现失败';
			break;
		default :
			return '返现';
			break;
	}
}

function get_type_consume($id = 1) {
	switch($id) {
		case 1 :
			return '分佣';
			break;
		case 2 :
			return '退款';
			break;
		case 3 :
			return '商城消费';
			break;
		case 4 :
			return '退货';
			break;
		default :
			return '完成任务小卡奖励';
			break;
	}
}

function get_type_gongyi($id = 1) {
	switch($id) {
		case 1 :
			return '分佣';
			break;
		case 2 :
			return '退款';
			break;
		case 3 :
			return '商城消费';
			break;
		default :
			return '退货';
			break;
	}
}
  
function get_int($ints) {
	return floor($ints);
}


function get_baifenbi($ints) {
	$mo = $ints/10000;
	if($mo > 1){
		return 100;
	}elseif($mo > 0.0001){
		return 10;
	}elseif($mo > 0.2){
		return 20;
	}elseif($mo > 0.3){
		return 30;
	}elseif($mo > 0.4){
		return 40;
	}elseif($mo > 0.5){
		return 50;
	}elseif($mo > 0.6){
		return 60;
	}elseif($mo > 0.7){
		return 70;
	}elseif($mo > 0.8){
		return 80;
	}elseif($mo > 0.9){
		return 90;
	}else{
		return 0;
	}
	
}
//广告分类
function get_ads($id = 1) {
	switch($id) {
		case 1 :
			return '首页广告';
			break;
		case 2 :
			return '健康广告';
			break;
		case 3 :
			return '商城广告';
			break;
		default :
			return '其它广告';
			break;
	}
}

//判断是微信还是支付波啊打开1支付宝2微信
function get_brower_type(){
	if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
		return 2;
	}elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
		return 1;
	}
	return 0;
}
//获取openid
function user_wx_id($code){
	$wx_pay_info = config('wxpay');
	$curl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$wx_pay_info['APPID']."&secret=".$wx_pay_info['APPSECRET']."&code=$code&grant_type=authorization_code";
	$weixin =  file_get_contents($curl);//通过code换取网页授权access_token
	$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
	$array = get_object_vars($jsondecode);//转换成数组
	$openid = $array['openid'];//输出openid
	return $openid;
}

/**
 * 获取支付宝key
 * 支付宝请求秘钥$aliy_key
 */
function user_ali_id($aliy_key){
	import("payment.dpay.aop.AopClient");
	import("payment.dpay.aop.request.AlipaySystemOauthTokenRequest");
	$code = $aliy_key;//获取code
	$aop = new \AopClient ();
	$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
	$aop->appId = config('alipay_appid');
	$aop->rsaPrivateKey = "MIIEowIBAAKCAQEAtub3Q1jvEjdclWiITaCmFGPs5efB3bDUlXKbUaMQfF7FPhcPtcmH/xbbI5bTgwtdgz8SjM2GNYon4vkpcjHUYzQmbwxcjcWr5vd2hkh1mAzVRHj6V3M3lfuudInXcx+VINd7N1SiPsyW/5YsWKduEmTdXQtGkru3GGFBnDCZjyGs/TPeM0Lizgh7Sm81m6JoeQpI70kBo1fNV8aPmYaRsqg2pZXPeSwA1TrGJyiv9TcECdVoQm6Q9ZRRdT5jZCokodaUVprWYg+Avs43fDSo7dgpQqYE0w0BbjXlqobCuFDNYvsZDxMyUZGSOTk3fIRp8ZWa/ndXl7f58zI+7tii+wIDAQABAoIBAQCa+iurojC4o7ZMVw2fkS8Ief8ic3TejtYiZ8DZtKzkZT0GNm42X7RfXhODHWrNUBUFf60NJ5y/wve3J96Jh1VqVab3U2cdLdBR3X9NmxohI0aWRVgCP3trF54j2yR2xN0MvekG4iyzv5F2sd2TpRLsfRDgpQxAitRC0S3R1ZBYKQXntPtVf5mlO2YF1OWMZ90nyK+zxZf6rx+nhmSMn9h4KMqBsHJFqU5AY2nz27imf2jQz1BokIDJIPRYaFOPqz0dDZkaV7oXsDXLhOcGfxAkCbIxkDOUpRX2rLNiTBnEIqSpNCJ+TEccUvX1XGusQy37PmShGL7JNAuuaxOa2l5hAoGBAOnXRg/ilSF/01I5biQ7wmLP0SRdQKIF60bX7MBTMuqQvVcfYzn3L12RQzUg/pPrNiLm35vSo3SMtozbMNKmTGZJzF7juFrj9zKzgR4DcuU+p0pAbi8M2He1FEu/KPQoKyhuZaSDKHf2YuTUxljqZ/vBb+rhJZ6MCWCxyXkRVbuLAoGBAMg7+YK3sLkqOeJwiKNaxRZyovDjylUvjWvKXNX36a52YaJEt4KQiu57+degJCkFGkncnW/eIWU7QqgOA/CVmTKojjY98Z150MAPk3lMePNVTh27TNG8jtYq/KWcR2zDv/rqNSJwlcW1Oti08V00kJos04YZ2vkxzZ7Azd3HImRRAoGAbAmo9hfifOq48MlV6OmvQsXvQ9TN0s3XSRDj8mu+H3+l6wW2a4aX3KwLmBVZaXAHwBJZB35HRMbqZKO0p+5rZ+r6wHCHsX6XrFYg9oPzZpUO55BjF9vge1YvPVvhiQSyA+kVju+GF/6+7CieR2BtkHRrx+Ij5l+eyYz6n7Pxn0cCgYABecet+fKYesIwdAndwlZ/gtrGkbc1B4OwTq5+eTREr+SqUH1VvgD4HvvJZgm+L6Zw8upKH8X5PAWSvX+z7zZQ1EMwDSbRtUsfjz3UAAdIK9HGkFHRneUjmO+BvPQdzheFHuLDXTcNXPeRD0xUFoYWTMxGSbx+Z6qPR/Z8cvJC8QKBgC4KwCQMhGbP/Y/07FNgsZXBrbRZ4J97280k56YAU9p099S5oKKKNrJmgK8hNMknyIPVf96QBnOE9Pcwdbf2fUO7aCVwkJUcUL2y6X5cSzYoM6Wxbf9h2KBubzEjDamwEKlWgkSHTq0Z3wthlW3uiVo0dnVPcEhnJM/38eFdlICv";
	$aop->alipayrsaPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjkJlBPWQkWe+ExtL1z2XMIjsvOwvduz1CVKgxlwfPGbzzBVsmXzEjdnIjHpF6KjGo8MwaGd9wRmsVM3kqMvuHDbBfk4egoKClgzXLYPuUrNK6h5bsz6WY1/8tBlg2xMVg2AabNdHSEwI8z6PDELcfVmkkcOfS+fGzuCnvSYeEIpGzz1uQQPSbHfxNxCcCdkJ0SZfjduX2augFZ+1L/sorJgLxfNxWBcNCyJST1M3Eix5NHOA6iR3iSvkV4z0Yes1uMyv4Rp3nHFs8KMOZOsTmrqvpLWrhEkz7EH5j+v7fjRVmgb42Whz3HxP9tuhDgFC7YpbCfKURZZFqWYUTpTLvQIDAQAB";
	
	$aop->apiVersion = '1.0';
	$aop->signType = 'RSA2';
	$aop->postCharset='UTF-8';
	$aop->format='json';
	
	$request = new \AlipaySystemOauthTokenRequest ();
	$request->setGrantType("authorization_code");
	$request->setCode($code);
	$result = $aop->execute ( $request); 
	$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
	$resultCode = $result->$responseNode->user_id;
	
	return  $resultCode;
}



/******************************====  公共函数 end ======******************************/
